
#include <base/engine.h>
#include <base/timing.h>

HANDLE app_thread;
Timer timey;

long InitializeEngine(HWND application, HWND window, LPTHREAD_START_ROUTINE app){
	InitD3D();
  Device * d = GetDevice(AddDevice());
  d->createWindowed(window);

  //InitInput(application);
  InitInterface(d, 1.0);
  PrintConsoleLine("Interface initialized");
  
  PrintConsoleLine("Initializing input handler");
  //InitInputHandler();

  PrintConsoleLine("Initializing sound");

  PrintConsoleLine("Creating application thread");
  app_thread = CreateThread(NULL, 0, app, application, 0, NULL);

  return 0;
}

long IterateEngine() {
  const events::Event * event;
  Device * d = GetDevice(0);

  //GetInputData();
  //HandleInput();

  //event handling!
  while(event = events::PeekEvent(events::MAIN_QUEUE))
  {
    const char * type = event->type();

    if(events::CompareEvents(type, events::PRINTCONSOLE_EVENT))
    {
      PrintConsoleLine(((events::PrintConsole *)event)->getMessage());
    }
    else if(events::CompareEvents(type, events::LOADRESOURCE_EVENT)) {
      PrintConsoleLine(std::string("Loading ") + ((events::LoadResource *)event)->getFilename());
      long index = LoadResourceFromFile(((events::LoadResource *)event)->getFileType(), ((events::LoadResource *)event)->getFilename(), d);
      events::Fire(new events::ReportResourceID(index));
    }
    events::PopEvent(events::MAIN_QUEUE);
  }

	d->beginScene();
    //draw the scene graph from the app thread
    d->setView(0, 0);
    RenderGraph(d);
    DrawInterface(d, timey.GetTicks());
	d->endScene();

   timey.Reset();
  return 0;
}

long DestroyEngine(){

  //destroy application thread (give it a few seconds
  events::Fire(new events::EndThread(events::APP_QUEUE));
  DWORD exitCode;
  unsigned long timing = GetTickCount();
  do
  {
    GetExitCodeThread(app_thread, &exitCode);
    if(GetTickCount() - timing > 10000) {
      PrintConsoleLine("Forcing app thread to close");
      break;
    }
  } while(exitCode == STILL_ACTIVE);
  CloseHandle(app_thread);

  //clean things up
  DestroyResources();
  DestroyInterface();
  RemoveDevice(0);
  DestroyD3D();

  return 0;
}
